<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .chat{
            width: 300px;
            height: 500px;
            text-align: center;
            margin: 0 auto;
            border: 1px solid #ccc;
        }
        .message{
            width: 100%;
            height: 460px;
        }
        #table{
            border: 1px solid
        }
    </style>
</head>
<body>
    <div class="chat">
        <select name="" id="select" onchange="console.log()">
            
        </select>
        <div class="message"></div>
        <div>我是<span id="_id"></span></div>
        <input id="text" type="text" placeholder="请输入聊天信息">
        <button onclick="chat()">发送信息</button>
    </div>

    <!-- <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script> -->
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <!-- <script src="./javascripts/underscore.min.js"></script> -->
    <script>
        let message = document.getElementsByClassName('message')[0]
        let socket = io.connect('http://localhost:3000');
        //
        let userid = this.getUuid()
        let userLs = []

        socket.emit('login', userid);
        //从服务端接收数据
        socket.on('login',function (data) {
            document.getElementById("_id").innerHTML = data;
        })
        socket.on('message',function (data) {
            message.innerHTML += `${data.id}:${data.message}` + '<br>';
        })
        socket.on('sayTo',function (data) {
            message.innerHTML += `${data.id}:${data.message}` + '<br>';
        })
        socket.on('userLs',function (data) {
            console.log(data)
            $("#select").append(`<option value="">所有人</option>`)
            if(data.length > 0){
                for(let item of data){
                    $("#select").append(`<option value="${item.id}">${item.id}</option>`)
                }
            }
        })
        socket.on('error', function(msg) {
            //错误提示     
            alert(msg)     
        });
        function chat(){
            let text = document.getElementById('text').value
            if(!text){
                alert('不能发送空消息！')
                return
            }
            //向服务端发送数据
            if($('#select option:selected').val()){
                console.log($('#select option:selected').val())
                // return
                socket.emit('sayTo', {id:$('#select option:selected').val(),message:text});
            }else{
                socket.emit('message', {message:text});
            }
        }
        function getUuid () {
            function S4 () {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
            }
            return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
        }
    </script>
</body>
</html>